from configparser import ConfigParser
import os,pymysql
import traceback
class ReadConfig:
    def __init__(self,file):
        self.config = ConfigParser()
        config_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + file
        self.config.read(config_path,encoding='utf-8')     # 设置中文编码
    def get_option(self,option):
        sections = self.config.sections()      # 获取所有的节
        for section in sections:        # 遍历访问所有的节点
            if self.config.has_option(section,option):      # 判断这个选项是否存在于节
                return self.config.get(section,option)      # 存在则返回这个value
class DB:
    def __init__(self,database_name):
        r = ReadConfig('config.ini')
        self.database = database_name
        # 获取数据库ip
        self.host = r.get_option(database_name +"_host")
        """
        r.get_option("crmeb_host")  ===》 8.148.229.201
        """
        # 获取数据库账号
        self.user = r.get_option(database_name +"_user")
        """
        r.get_option("crmeb_user")  ===》 root
        """
        # 获取数据库密码
        self.password = r.get_option(database_name +"_password")
    def connect(self):
        self.db = pymysql.connect(user=self.user,password=self.password,host=self.host,database=self.database,cursorclass =
        pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def searchAll(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()
    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchOne()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()
    def __edit(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
            traceback.print_exc()
        finally:
            self.close()
    def insert(self,sql):
        return self.__edit(sql)
    def delete(self,sql):
        return self.__edit(sql)
    def update(self,sql):
        return self.__edit(sql)

# if __name__ == '__main__':
#     d1 = DB("crmeb")
#     print(d1.searchAll(f"select id from eb_user_group where group_name like '%大傻蛋'")[0]['id'])


















